package com.chen.blog.controller;


import com.chen.blog.common.api.CommonResult;
import com.chen.blog.common.component.ImgUtil;
import com.chen.blog.common.constant.MessageConstant;
import com.chen.blog.config.security.component.AuthenticationUtil;
import com.chen.blog.model.Admin;
import com.chen.blog.service.AdminService;
import com.chen.blog.vo.LoginVo;
import com.chen.blog.vo.PwdVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chen
 * @since 2022-01-24
 */
@Api(tags = "管理员管理 AdminController")
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private AuthenticationUtil authenticationUtil;

    @Autowired
    private ImgUtil imgUtil;

    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVo loginVo) {
        if (adminService.getAdminByUserName(loginVo.getUsername()) == null) {
            return CommonResult.error(MessageConstant.ADMIN_LOGIN_FAIL);
        }
        return authenticationUtil.login(loginVo);
    }

    @ApiOperation("获取当前登录用户详情")
    @GetMapping("/detail")
    public Admin detail() {
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null == admin) {
            return null;
        }
        admin.setPassword(null);
        return admin;
    }

    @ApiOperation("更新密码")
    @PutMapping("/pwd")
    public CommonResult updatePwd(@RequestBody PwdVo pwdVo) {
        return adminService.updatePwd(pwdVo);
    }

    @ApiOperation("更新头像")
    @PostMapping("/pic/{id}")
    public CommonResult updatePic(@RequestParam("file") MultipartFile file, @PathVariable Integer id) {
        return imgUtil.updatePic(file, id, adminService.getById(id));
    }

}
